const ExcelJS = require('exceljs');

// Función para cargar stopwords desde un archivo Excel
async function loadStopwords() {
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.readFile('stopwords.xlsx');
  const worksheet = workbook.getWorksheet(1);

  let stopWords = new Set();
  worksheet.eachRow((row) => {
    stopWords.add(row.getCell(1).text.toLowerCase()); // Asume que las stopwords están en la primera columna
  });

  return stopWords;
}

// Función para cargar el archivo Excel de posts
async function loadExcel() {
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.readFile('EWatchReports.xlsx');
  const worksheet = workbook.getWorksheet(1);

  let posts = [];
  worksheet.eachRow((row, rowNumber) => {
    posts.push({ text: row.getCell(1).text, reportNumber: rowNumber });
  });

  return posts;
}

// Función para contar palabras
function processWords(posts, stopWords) {
  let wordCounts = {};
  let wordReports = {};

  posts.forEach(({ text, reportNumber }) => {
    let words = text.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(" ");
    
    words.forEach(word => {
      if (!stopWords.has(word)) {
        wordCounts[word] = (wordCounts[word] || 0) + 1;

        if (!wordReports[word]) wordReports[word] = [];
        wordReports[word].push(text);  // Agregar el post completo en lugar del número de reporte
      }
    });
  });

  return { wordCounts, wordReports };
}

// Función para contar bigramas
function processBigrams(posts, stopWords) {
  let bigramCounts = {};
  let bigramReports = {};

  posts.forEach(({ text, reportNumber }) => {
    let words = text.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(" ");
    let filteredWords = words.filter(word => !stopWords.has(word));

    for (let i = 0; i < filteredWords.length - 1; i++) {
      const bigram = `${filteredWords[i]} ${filteredWords[i + 1]}`;
      bigramCounts[bigram] = (bigramCounts[bigram] || 0) + 1;

      if (!bigramReports[bigram]) bigramReports[bigram] = [];
      bigramReports[bigram].push(text);  // Agregar el post completo en lugar del número de reporte
    }
  });

  return { bigramCounts, bigramReports };
}

// Función para guardar los resultados en un archivo Excel
async function saveResultsToExcel(wordData, bigramData) {
  const workbook = new ExcelJS.Workbook();

  // Pestaña de palabras top
  const wordsSheet = workbook.addWorksheet('Top Words');
  wordsSheet.columns = [
    { header: 'Word', key: 'word', width: 30 },
    { header: 'Count', key: 'count', width: 10 },
    { header: 'Reports', key: 'reports', width: 50 }
  ];

  Object.entries(wordData.wordCounts).forEach(([word, count]) => {
    wordsSheet.addRow({
      word,
      count,
      reports: wordData.wordReports[word].join(' // ')  // Juntar los textos de los reportes con "//"
    });
  });

  // Pestaña de bigramas
  const bigramsSheet = workbook.addWorksheet('Top Bigramas');
  bigramsSheet.columns = [
    { header: 'Bigrams', key: 'bigram', width: 30 },
    { header: 'Count', key: 'count', width: 10 },
    { header: 'Reports', key: 'reports', width: 50 }
  ];

  Object.entries(bigramData.bigramCounts).forEach(([bigram, count]) => {
    bigramsSheet.addRow({
      bigram,
      count,
      reports: bigramData.bigramReports[bigram].join(' // ')  // Juntar los textos de los reportes con "//"
    });
  });

  await workbook.xlsx.writeFile('EWatchAnalysis.xlsx');
  console.log('Saved File - EWatch Analysis.xlsx');
}

// Función principal
async function main() {
  // Cargar stopwords desde el archivo Excel
  const stopWords = await loadStopwords();

  // Cargar posts
  const posts = await loadExcel();

  // Procesar palabras y bigramas con las stopwords cargadas
  const wordData = processWords(posts, stopWords);
  const bigramData = processBigrams(posts, stopWords);

  // Guardar resultados en Excel
  await saveResultsToExcel(wordData, bigramData);
}

main();
